package com.easytake.emotioncat.config;

import com.easytake.emotioncat.dto.Response;
import com.easytake.emotioncat.exception.AuthorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Response<?> serverExceptionHandler(HttpServletRequest httpServletRequest, Exception e) {
        logger.error("服务错误:", e);
        return Response.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务出错");
    }

    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Response<?> paramExceptionHandler(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
        logger.error("参数错误:", e);
        return Response.fail(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = AuthorException.class)
    public Response<?> authorExceptionHandler(HttpServletRequest httpServletRequest, AuthorException e) {
        logger.error("认证错误:", e);
        return Response.fail(e.getCode(), e.getErrorMsg());
    }

    /**
     * @param httpServletRequest
     * @param e
     * @return
     * @Validate注解校验异常拦截
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public Response<?> validateExceptionHandler(HttpServletRequest httpServletRequest, BindException e) {
        logger.error("参数错误:", e);
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errMsg = new StringBuilder(bindingResult.getFieldErrors().size() * 16);
        errMsg.append("Invalid request:");
        for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
            if (i > 0) {
                errMsg.append(",");
            }
            FieldError error = bindingResult.getFieldErrors().get(i);
            errMsg.append(error.getField() + ":" + error.getDefaultMessage());
        }
        return Response.fail(HttpStatus.BAD_REQUEST.value(), errMsg.toString());
    }
}
